package com.linkoog.devtools.code_generator.wizard.generate.database.table.dialog;

import com.linkoog.devtools.code_generator.Bundle;
import com.linkoog.devtools.code_generator.database.domain.ConnectionInfo;
import com.linkoog.devtools.code_generator.database.domain.DbType;
import com.linkoog.devtools.code_generator.database.dao.DatabaseDao;
import com.linkoog.devtools.code_generator.database.dao.DatabaseDaoFactory;
import com.linkoog.devtools.code_generator.wizard.generate.database.table.dialog.datasource.panel.DbTypeComboBoxCellRender;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.function.Consumer;

/**
 * @author xiaoyu
 */
public class ConnectionOperationDialog extends DialogWrapper {
    private JPanel myMainPanel;
    private JPanel myConnPanel;
    private JPanel myActionPanel;
    private JLabel myNameLabel;
    private JTextField myNameField;
    private JLabel myHostLabel;
    private JTextField myHostField;
    private JTextField myPortField;
    private JTextField myUsernameField;
    private JPasswordField myPasswordField;
    private JLabel myPortLabel;
    private JLabel myUsernameLabel;
    private JLabel myPasswordLabel;
    private JButton myTestButton;
    private JComboBox dbTypeComboBox;
    private volatile boolean isRepaint = true;

    private Consumer<ConnectionInfo> connectionInfoConsumer;

    public ConnectionOperationDialog(JComponent jComponent, Consumer<ConnectionInfo> connectionInfoConsumer) {
        this(jComponent, connectionInfoConsumer, null);
    }


    public ConnectionOperationDialog(@NotNull JComponent jComponent, @NotNull Consumer<ConnectionInfo> connectionInfoConsumer, ConnectionInfo connectionInfo) {
        super(jComponent, false);
        $$$setupUI$$$();
        setTitle("添加连接");
        myMainPanel.setMinimumSize(new Dimension(250, 160));
        this.connectionInfoConsumer = connectionInfoConsumer;


        dbTypeComboBox.setRenderer(new DbTypeComboBoxCellRender());
        for (DbType dbType : DbType.values()) {
            dbTypeComboBox.addItem(dbType);
        }

        if (connectionInfo != null) {
            setTitle("修改连接");
            myNameField.setText(connectionInfo.getName());
            dbTypeComboBox.setSelectedItem(connectionInfo.getDbType());
            myHostField.setText(connectionInfo.getHost());
            myPortField.setText(connectionInfo.getPort().toString());
            myUsernameField.setText(connectionInfo.getUsername());
            myPasswordField.setText(connectionInfo.getPasswd());
        }

        myTestButton.addActionListener(e -> {
            isRepaint = false;
            Container contentPane = getContentPane();
            Graphics graphics = contentPane.getGraphics().create();
            graphics.setColor(new Color(255, 255, 255, 255 / 3));
            graphics.fillRect(0, 0, contentPane.getWidth(), contentPane.getHeight());
            try {
                ConnectionInfo connTemp = new ConnectionInfo();
                connectionInfo.setDbType((DbType) dbTypeComboBox.getSelectedItem()).setName(myNameField.getText()).setHost(myHostField.getText()).setPort(Integer.valueOf(myPortField.getText())).setUsername(myUsernameField.getText()).setPasswd(new String(myPasswordField.getPassword()));

                DatabaseDao databaseDao = DatabaseDaoFactory.create(connTemp);
                boolean test = databaseDao.validConnection();
                if (test) {
                    Messages.showInfoMessage(myMainPanel, "连接成功", "");
                } else {
                    Messages.showErrorDialog(myMainPanel, "连接失败");
                }
            } catch (Exception ex) {
                Messages.showErrorDialog(myMainPanel, ex.getMessage());
            } finally {
                isRepaint = true;
                graphics.dispose();
                contentPane.repaint();
            }
        });
        init();
    }

    @Nullable
    @Override
    protected ValidationInfo doValidate() {
        ValidationInfo info = null;
        if (StringUtil.isEmptyOrSpaces(myNameField.getText())) {
            info = new ValidationInfo(Bundle.message("validate.conn.name"));
        }
        if (info == null && StringUtil.isEmptyOrSpaces(myHostField.getText())) {
            info = new ValidationInfo(Bundle.message("validate.conn.host"));
        }
        String portText = myPortField.getText();
        if (info == null && StringUtil.isEmptyOrSpaces(portText)) {
            info = new ValidationInfo(Bundle.message("validate.conn.port"));
        }
        if (info == null && !StringUtils.isNumeric(portText)) {
            info = new ValidationInfo(Bundle.message("validate.conn.portnum"));
        }
        if (info == null && StringUtil.isEmptyOrSpaces(myUsernameField.getText())) {
            info = new ValidationInfo(Bundle.message("validate.conn.username"));
        }
		/*if (info == null) {
			if (myPasswordField.getPassword() == null || StringUtil.isEmptyOrSpaces(new String(myPasswordField.getPassword()))) {
				info = new ValidationInfo(CrudBundle.message("validate.conn.password"));
			}
		}*/
        return info;
    }


    @Override
    public void doCancelAction() {
        super.doCancelAction();
    }

    @Override
    protected void doOKAction() {
        ConnectionInfo connectionInfo = new ConnectionInfo((DbType) dbTypeComboBox.getSelectedItem(), myNameField.getText(), "", myHostField.getText(), Integer.valueOf(myPortField.getText()), myUsernameField.getText(), new String(myPasswordField.getPassword()), "", "");
        connectionInfoConsumer.accept(connectionInfo);
        super.doOKAction();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        return myMainPanel;
    }

    private void createUIComponents() {
        myTestButton = new JButton() {
            private static final long serialVersionUID = -137016959157649166L;

            @Override
            public void repaint() {
                if (isRepaint) {
                    super.repaint();
                }
            }
        };
    }


    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        createUIComponents();
        myMainPanel = new JPanel();
        myMainPanel.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
        myConnPanel = new JPanel();
        myConnPanel.setLayout(new GridLayoutManager(7, 2, new Insets(0, 0, 0, 0), -1, -1));
        myMainPanel.add(myConnPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(24, 171), null, 0, false));
        myNameLabel = new JLabel();
        myNameLabel.setText("连接名称: ");
        myConnPanel.add(myNameLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final Spacer spacer1 = new Spacer();
        myConnPanel.add(spacer1, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        myNameField = new JTextField();
        myNameField.setText("");
        myConnPanel.add(myNameField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        myHostLabel = new JLabel();
        myHostLabel.setText("主机: ");
        myConnPanel.add(myHostLabel, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        myHostField = new JTextField();
        myHostField.setText("localhost");
        myConnPanel.add(myHostField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        myPortLabel = new JLabel();
        myPortLabel.setText("端口");
        myConnPanel.add(myPortLabel, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        myPortField = new JTextField();
        myPortField.setText("3306");
        myConnPanel.add(myPortField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        myUsernameLabel = new JLabel();
        myUsernameLabel.setText("用户名");
        myConnPanel.add(myUsernameLabel, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        myUsernameField = new JTextField();
        myUsernameField.setText("root");
        myConnPanel.add(myUsernameField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        myPasswordLabel = new JLabel();
        myPasswordLabel.setRequestFocusEnabled(true);
        myPasswordLabel.setText("密码");
        myConnPanel.add(myPasswordLabel, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        myPasswordField = new JPasswordField();
        myConnPanel.add(myPasswordField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        myTestButton.setText("测试连接");
        myConnPanel.add(myTestButton, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JLabel label1 = new JLabel();
        label1.setText("数据库类型");
        myConnPanel.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        dbTypeComboBox = new JComboBox();
        myConnPanel.add(dbTypeComboBox, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        myActionPanel = new JPanel();
        myActionPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
        myMainPanel.add(myActionPanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return myMainPanel;
    }

}
